<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property string $id
 * @property string $role
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $fullname
 * @property string $avatar
 * @property string $phone_no
 * @property string $dob
 * @property string $address
 * @property integer $gender
 * @property integer $status
 * @property integer $login_type
 * @property string $last_visited
 * @property string $created_at
 *
 * The followings are the available model relations:
 * @property Collection[] $collection
 * @property Comment[] $comment
 * @property Image[] $image
 * @property ImageUserFollow[] image_follow
 * @property Style[] style
 * @property UserActive[] $userActive
 * @property UserFollow[] $userFollow
 * @property UserNotify[] $userNotify
 */
class User extends CActiveRecord {

    const OFFLINE = 0;
    const ONLINE_PC = 1;
    const ACCOUNT_LOCKED = 0;
    const ACCOUNT_ACTIVE = 1;
    const ACCOUNT_NOT_ACTIVE = 2;

    public $oldPassword;
    public $newPassword;
    public $newPassword_repeat;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'tbl_user';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email, avatar, username, fullname, password', 'required', 'on' => 'create'),
            array('oldPassword, newPassword, newPassword_repeat', 'required', 'on' => 'changePassword'),
            array('newPassword, newPassword_repeat', 'required', 'on' => 'createPassword'),
            array('newPassword_repeat', 'compare', 'compareAttribute' => 'newPassword'),
            array('gender, status, login_type', 'numerical', 'integerOnly' => true),
            array('avatar', 'file', 'types' => 'jpg, gif, png', 'allowEmpty' => true, 'maxSize' => 1024 * 1024 * 2, 'tooLarge' => 'File không được quá 2Mb !', 'on' => 'edit'),
            array('email', 'email'),
            array('username, password, email', 'length', 'max' => 40),
            array('fullname, avatar, address', 'length', 'max' => 100),
            array('phone_no', 'length', 'max' => 11),
            array('dob', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, username, password, email, fullname, avatar, phone_no, dob,  address, gender, status, login_type, last_visited, created_at', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'collection' => array(self::HAS_MANY, 'Collection', 'user_created'),
            'comment' => array(self::HAS_MANY, 'Comment', 'user_id'),
            'style' => array(self::HAS_MANY, 'UserStyle', 'user_id'),
            'image' => array(self::MANY_MANY, 'Image', 'user_created'),
            'image_follow' => array(self::MANY_MANY, 'ImageUserFollow', 'user_id'),
            'userActive' => array(self::HAS_MANY, 'UserActive', 'user_id'),
            'userFollow' => array(self::HAS_MANY, 'UserFollow', 'follower'),
            'userNotify' => array(self::HAS_MANY, 'UserNotify', 'to_user'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'role' => 'Quyền',
            'username' => 'Tên tài khoản',
            'password' => 'Mật khẩu',
            'email' => 'Email',
            'fullname' => 'Họ và tên',
            'avatar' => 'Ảnh đại diện',
            'phone_no' => 'Số điện thoại',
            'dob' => 'Ngày sinh',
            'address' => 'Địa chỉ',
            'gender' => 'Giới tính',
            'status' => 'Trạng thái',
            'login_type' => 'Login Type',
            'last_visited' => 'Đăng nhập lần cuối',
            'created_at' => 'Ngày tạo',
            'newPassword' => 'Mật khẩu mới',
            'newPassword_repeat' => 'Xác nhân mật khẩu mới',
            'oldPassword' => 'Mật khẩu cũ'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('role', $this->role, true);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('fullname', $this->fullname, true);
        $criteria->compare('avatar', $this->avatar, true);
        $criteria->compare('phone_no', $this->phone_no, true);
        $criteria->compare('dob', $this->dob, true);
        $criteria->compare('address', $this->address, true);
        $criteria->compare('gender', $this->gender);
        $criteria->compare('status', $this->status);
        $criteria->compare('login_type', $this->login_type);
        $criteria->compare('last_visited', $this->last_visited, true);
        $criteria->compare('created_at', $this->created_at, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function getFullName($id) {
        if ($id == null) {
            return '';
        }
        $user = User::model()->findByPk($id);
        return $user->fullname;
    }

    public function getRole($id) {
        if ($id == null) {
            return '';
        }
        $user = User::model()->findByPk($id);
        return $user->role;
    }

    public function getUserName($id) {
        if ($id == null) {
            return '';
        }
        $user = User::model()->findByPk($id);
        return $user->username;
    }

    public function getUserById($id) {
        if ($id == null) {
            return '';
        }
        $user = User::model()->findByPk($id);
        return $user;
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $id of current user.
     * @return UserActive[] the static model class
     */
    public static function getNotify($id) {
//        $user = User::model()->findByPk($id);
        $lstFollowedID = array();
        $modelodel = array();
        $listImageFollow = ImageUserFollow::model()->findAll("user_id=:id", array(
            ':id' => $id
        ));
        if ((!is_null($listImageFollow)) && sizeof($listImageFollow > 0)) {

            foreach ($listImageFollow as $followed) {
                $lstFollowedID [] = $followed->image_id;
            }
            $lstFollowed = implode(",", $lstFollowedID);
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id where t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.user_id = img_fl.user_id join tbl_user u on u.id = t.user_id where t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.image_id = img_fl.image_id join tbl_user u on u.id = t.user_id where img_fl.user_id =:id and t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status and t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
            $modelodel = UserActive::model()->findAllBySql($sql, array(
                ':id' => $id,
                ':active_type' => UserActive::COMMENT_IMG
                , ':user_status' => User::ACCOUNT_ACTIVE
                , ':img_status' => Image::IMAGE_ACTIVE
            ));
        }
        return $modelodel;
    }

    public static function getNotifyCount($id) {
//        $user = User::model()->findByPk($id);
        $readed = NotifyStatus::model()->findBySql("Select * From tbl_notify_status  Where user_id=:id and status=:status Order BY active_id DESC LIMIT 0,1", array(
            ':id' => $id,
            ':status' => NotifyStatus::READED
        ));
        $lstFollowedID = array();
        $modelodel = array();
        $listImageFollow = ImageUserFollow::model()->findAll("user_id=:id", array(
            ':id' => $id
        ));
        if ((!is_null($listImageFollow)) && sizeof($listImageFollow > 0)) {

            foreach ($listImageFollow as $followed) {
                $lstFollowedID [] = $followed->image_id;
            }
            $lstFollowed = implode(",", $lstFollowedID);
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id where t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.user_id = img_fl.user_id join tbl_user u on u.id = t.user_id where t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
            if ($readed) {
                $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.image_id = img_fl.image_id join tbl_user u on u.id = t.user_id where img_fl.user_id =:id and t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status and t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) and t.id >'.$readed->active_id.' ORDER BY active_at DESC LIMIT 0 , 10';
            } else {
                $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.image_id = img_fl.image_id join tbl_user u on u.id = t.user_id where img_fl.user_id =:id and t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status and t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
            }
            $modelodel = UserActive::model()->findAllBySql($sql, array(
                ':id' => $id,
                ':active_type' => UserActive::COMMENT_IMG
                , ':user_status' => User::ACCOUNT_ACTIVE
                , ':img_status' => Image::IMAGE_ACTIVE
            ));
        }
        return sizeof($modelodel);
    }

}